package cn.wgx.springsecuritystudy.web;


import cn.wgx.springsecuritystudy.service.UserService;
import cn.wgx.springsecuritystudy.util.ValidateCodeImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;


@Controller
public class HelloCtl {

    @Autowired
    UserService userService;

    @GetMapping(value = "/")
    public String g(){
        return "redirect:index.html";
    }

    @GetMapping(value = "/admin")
    @ResponseBody
    public String g1(){
        return "admin role";
    }

    @GetMapping(value = "/user")
    @ResponseBody
    public Map g2(){
        return userService.g();
    }

    @GetMapping(value = "/guest")
    @ResponseBody
    public String g3(){
        return "guest role";
    }


    @RequestMapping(value = "img/vCode", method = RequestMethod.GET)
    public void validateCode(HttpServletResponse response, HttpSession session){
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ValidateCodeImageUtil v = new ValidateCodeImageUtil();
        String vCode = v.createVCode();
        BufferedImage image = v.createImage(vCode);
        OutputStream out = null;
        session.setAttribute(ValidateCodeImageUtil.vCodeParameter, vCode);
        try {
            out = response.getOutputStream();
            ImageIO.write(image, "JPEG", out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
